using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.XPath;
using System.Xml;
using Instedd.Labs.Geo.Library.Kml;
using System.Collections.Generic;
using Instedd.Labs.Forms.Library;
using System.Text;
using Instedd.Labs.Geo.Library.Kml.Styles;
using System.IO;

public partial class GetFeed : System.Web.UI.Page
{



    protected void Page_Load(object sender, EventArgs e)
    {
        KmlFormat kml = new KmlFormat();
        AddIconStyles(kml);
        Folder folder = new Folder("BioForms");
        folder.Placemarks.AddRange(GenerateKmlPlacemarks(kml));
        kml.Folders.Add(folder);

        if (Request.QueryString["c"] != null && Request.QueryString["c"].ToLower() == "ge")
        {
            // render the KML as an attachment so the user is asked to open/save the file and the locally
            // installed GE has a chance at opening it.
            GenerateKmlFeed(true, kml);
        }
        {
            GenerateKmlFeed(false, kml);
        }
    }

    List<Placemark> GenerateKmlPlacemarks(KmlFormat kml)
    {
        List<Placemark> placemarks = new List<Placemark>();

        using (IDataReader reader = SurveyManager.GetInstance().GetSurveysAsDataReader())
        {
            while (reader.Read())
            {
                Placemark placemark = CreatePlacemark(reader, kml);
                if (placemark != null)
                {
                    placemarks.Add(placemark);
                }
            }
        }

        return placemarks;
    }

    Placemark CreatePlacemark(IDataReader surveyReader, KmlFormat kml)
    {
        try
        {
            Survey survey = SurveyManager.GetInstance().CreateSurvey(surveyReader);
            if (survey.Latitude == null || survey.Longitude == null)
            {
                return null;
            }

            Placemark placemark = new Placemark(
                string.Format("{0}", survey.ID),
                string.Format(WebSurveyManager.GetInstance().PushpinDescriptionTemplate, 

                    survey.FirstName, survey.LastName, 
                    new Uri(this.Request.Url, string.Format("GetSurvey.aspx?surveyid={0}", survey.ID)).AbsoluteUri, survey.ID,
                    survey.Comments, 
                    survey.FollowUpComments,
                    survey.TotalExposed,
                    survey.TotalWell,
                    survey.TotalExposedNotIll,
                    survey.TotalExposedAndIll,
                    survey.TotalReceivedTreatment,
                    survey.TotalRecovered,
                    survey.TotalDeceased
                    ),
                new LatLong((double)survey.Latitude, (double)survey.Longitude),
                GetPlacemarkDate(survey));


            Instedd.Labs.Geo.Library.Kml.Styles.Style iconStyle = GetIconColor(survey, kml);
            if (iconStyle != null)
            {
                placemark.StyleUrl = iconStyle.ID;
            }
            
            return placemark;
        }
        catch
        {
            return null;
        }
    }

    private DateTime GetPlacemarkDate(Survey survey)
    {
        if ((survey.IsBlack || survey.IsBlue || survey.IsGreen || survey.IsPink || survey.IsPurple || survey.IsRed) && !DateTime.MinValue.Equals(survey.TimeOfOnset))
        {
            return survey.TimeOfOnset;
        }
        else
        {
            return survey.EnteredOn;
        }
    }

    private Instedd.Labs.Geo.Library.Kml.Styles.Style GetIconColor(Survey survey, KmlFormat kml)
    {
        string styleId = null;

        if (survey.IsBlack)
        {
            styleId = "blackIconStyle";
        }
        else if (survey.IsRed)
        {
            styleId = "redIconStyle";
        }
        else if (survey.IsPurple)
        {
            styleId = "purpleIconStyle";
        }
        else if (survey.IsBlue)
        {
            styleId = "blueIconStyle";
        }
        else if (survey.IsPink)
        {
            styleId = "pinkIconStyle";
        }
        else if (survey.IsGreen)
        {
            styleId = "greenIconStyle";
        }
        else if (survey.IsWhite)
        {
            styleId = "whiteIconStyle";
        }

        return kml.Styles.Find(delegate(Instedd.Labs.Geo.Library.Kml.Styles.Style s) { return s.ID == styleId; });
    }

    private T TryToParseValue<T>(IDataReader survey, string fieldName)
    {
        object value = survey[fieldName];

        if (value != DBNull.Value)
        {
            return (T)value;
        }

        return default(T);
    }


    void GenerateKmlFeed(bool renderAsAttachment, KmlFormat kml)
    {
        Response.Clear();
        if (renderAsAttachment)
        {
            Response.AppendHeader("Content-Disposition", "filename=BioForms.kml;attachment");
        }
        Response.Buffer = false;
        Response.ContentType = "application/xml";
        Response.ContentEncoding = Encoding.UTF8;

        StringBuilder sb = new StringBuilder();

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        XmlWriter writer = XmlWriter.Create(Response.OutputStream, settings);
        writer.Flush();

        KmlWriter kmlWriter = new KmlWriter();
        kmlWriter.WriteKml(writer, kml);
        writer.Flush();
        Response.End();
    }

    public void AddIconStyles(KmlFormat kml)
    {
        AddIconStyle("blackIconStyle", "black", kml);
        AddIconStyle("blueIconStyle", "blue", kml);
        AddIconStyle("greenIconStyle", "green", kml);
        AddIconStyle("pinkIconStyle", "pink", kml);
        AddIconStyle("purpleIconStyle", "purple", kml);
        AddIconStyle("redIconStyle", "red", kml);
        AddIconStyle("whiteIconStyle", "white", kml);
    }

    void AddIconStyle(string iconStyleId, string color, KmlFormat kml)
    {
        Instedd.Labs.Geo.Library.Kml.Styles.Style style = new Instedd.Labs.Geo.Library.Kml.Styles.Style(iconStyleId);
        style.IconStyle = new IconStyle();
        style.IconStyle.IconUri = new Uri(this.Request.Url, string.Format("img/icon_{0}.png", color));
        kml.Styles.Add(style);
    }
}

